<template>
    <el-dialog
            :title="title"
            :visible.sync="visible"
            :close-on-click-modal=false
            :close-on-press-escape=false
            :show-close=false
            width="70%">
        <el-row>
            <slot name="form"></slot>
        </el-row>
        <el-row>
            <el-col :span="8" >
                <el-row>
                    <el-form
                            label-width="100px"
                            :model="deptSearchForm"
                            ref="deptSearchForm">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item class="form-item" label="本级:" prop="searchValue">
                                    <el-switch v-model="localRegion" active-color="#13ce66" inactive-color="#DCDFE6"></el-switch>
                                </el-form-item>
                            </el-col>
                            <el-col :span="15" :offset="1">
                                <el-form-item class="form-item" label="部门名称:" prop="searchValue">
                                    <el-input placeholder="输入关键字进行过滤" v-model="searchValue"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-row>
                <el-row>
                    <div style="height:300px;overflow:auto;margin-left: 30px">
                        <el-tree class="filter-tree"
                                 :data="deptData"
                                 v-loading=loading
                                 :load="getDeptChildren"
                                 lazy
                                 node-key="id"
                                 ref="deptTree"
                                 accordion
                                 highlight-current
                                 :props="defaultProps"
                                 @node-click="nodeClick" v-show="lazy">
                        </el-tree>
                        <el-tree class="filter-tree"
                                 v-loading=loading
                                 :data="deptSynData"
                                 node-key="id"
                                 ref="deptSynTree"
                                 :default-expand-all="true"
                                 accordion
                                 highlight-current
                                 :props="defaultProps"
                                 @node-click="nodeClick" v-show="!lazy">
                        </el-tree>
                    </div>
                </el-row>
            </el-col>
            <el-col :span="16">
                <el-transfer
                        class="user-transfer"
                        v-model="selectUserIds"
                        :titles="['待选人员', '已选人员']"
                        :button-texts="['到左边', '到右边']"
                        :data="userData"
                        @left-check-change="leftChange"
                        @change="rightChange"
                        filterable
                        :filter-method="filterMethod"
                        ref="transfer">
                </el-transfer>
            </el-col>
            <el-col :span="8" style="display: none">
                <div style="margin-left: 10px;">
                    <h3>已选部门：</h3>
                    <el-tag v-if="deptName">{{deptName}}</el-tag>
                </div>
            </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancel()">取 消</el-button>
            <el-button type="primary" @click="confirm()">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {getDeptTree, getDeptXieTree, getUsersByUnitId} from "@/api/system";
    import {mapGetters} from "vuex";

    export default {
        name: "deptUserSelect",
        created() {
            this.lazy = true;
            this.debouncedGetSearchResult = _.debounce(this.getSearchResult, 500);
            this.localRegion = this.currentDeptLevel;
        },
        data() {
            return {
                deptId: '',
                deptName: '',
                searchValue: '',//搜索文字
                deptData: [],//组织机构树数据
                deptSynData: [],
                lazy: true,
                localRegion: true,
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                loading: false,
                deptSearchForm:{},
                userData:[],
                selectUserIds:[],
            }
        },
        props: {
            //最小部门类型，小于此类型的子部门不会显示，type为null会显示
            miniType: {
                type: Number,
                default: null
            },
            title: {
                type: String,
                default: '用户选择'
            },
            visible: {
                type: Boolean,
                default: false
            },
            currentDeptLevel: {
                type: Boolean,
                default: true
            },
            //选择的数量限制
            numLimit: {
                type: Number
            }
        },
        computed: mapGetters(["deptInfo"]),
        watch: {
            searchValue(newValue, oldValue) {
                if (newValue.length <= 1) {
                    this.lazy = true;
                } else if (newValue) {
                    this.lazy = false;
                    this.loading = true;
                    this.getSearchResult(newValue);
                }
            },
            localRegion(newValue, oldValue) {
                this.lazy = true;
                this.searchValue = "";
                this.loading = true;
                let queryParams = {
                    miniType: this.miniType
                };
                if (this.localRegion) {
                    queryParams.rootDeptId = this.deptInfo.deptId;
                } else{
                    queryParams.parentId = -1;
                }
                getDeptTree(queryParams).then(response => {
                    this.loading = false;
                    this.deptData = response.data.data;
                })
            }
        },
        methods: {
            // 获取组织机构树
            getSearchResult(value) {
                let param = {};
                param.name = value;
                if (this.localRegion) {
                    param.areaCode = this.deptInfo.areaCode
                }
                getDeptXieTree(param).then(response => {
                    this.loading = false;
                    this.deptSynData = response.data.data;
                })
            },
            // 获取组织机构树
            getDeptChildren(node, resolve) {
                this.loading = true;
                let queryParams = {
                    miniType: this.miniType
                };

                if(node.level == 0) {
                    if (this.localRegion) {
                        queryParams.rootDeptId = this.deptInfo.deptId;
                    } else{
                        queryParams.parentId = -1;
                    }
                }else {
                    queryParams.parentId = node.data.id
                }

                getDeptTree(queryParams).then(response => {
                    this.loading = false;
                    resolve(response.data.data)
                })
            },
            //组织机构树点击事件
            nodeClick(data) {
                this.deptId = data.id;
                this.deptName = data.name;
                if (data.id != null && data.id != undefined) {
                    getUsersByUnitId(data.id)
                        .then(response => {
                            this.userData = response.data.data;
                            this.selectUserIds = [];
                        });
                }
            },
            cancel(){
                this.$emit('cancel')
            },
            confirm() {
                //检查数量
                let numLimit = this.numLimit;
                if(this.selectUserIds != null && numLimit != null && this.selectUserIds.length > numLimit){
                    this.$notify({
                        title: '错误',
                        message: '最多选择' + numLimit + '个用户',
                        type: 'error',
                        duration: 2000
                    });
                    return false;
                }

                //获取用户名
                let userData = this.userData;
                let userMap = {};
                if (userData != null && Array.isArray(userData) && userData.length > 0) {
                    for (let user of userData) {
                        userMap[user.key] = user.label;
                    }
                }
                let userNames = [];
                for (let userId of this.selectUserIds) {
                    let username = userMap[userId];
                    if (username == null) {
                        username = userId;
                    }
                    userNames.push(username);
                }
                this.$emit('afterSelect', this.selectUserIds, userNames);
            },
            leftChange(key){

            },
            rightChange(key){

            },
            filterMethod(query, item) {
                return item.label.indexOf(query) > -1;
            },
        }
    };
</script>

<style lang="scss" scoped>
    .el-tree > .el-tree-node {
        min-width: 100%;
        min-height: 100%;
        display: inline-block;
    }

    .user-transfer{
        text-align: left;

        /deep/ .el-transfer-panel{
            width: 270px;
        }

        /deep/ .el-transfer-panel__body{
            height: 315px;
        }

        /deep/ .el-transfer-panel__list{
            height: 265px;
        }
        /deep/.el-transfer__buttons {
            width: 110px;
            .el-button:first-child{
                margin-left: 10px;
            }
            .el-button:nth-child(2){
                padding-right: 25px;
            }
        }
    }
    /deep/.el-switch__core{
        position: relative;
        left: -10px;
    }
</style>
